<template>
  <div class="main-container screen-management">
    <div class="container">
      <div class="sidebar-container" :class="{ collapsed: sidebarCollapsed }">
        <el-scrollbar>
          <el-menu
            ref="screenManagerMenu"
            class="screenManagerMenu"
            :class="{ 'menu-collapsed': sidebarCollapsed }"
            :default-active="menuActive"
          
            :unique-opened="false"
            @open="handleSubMenuOpen"
            @close="handleSubMenuClose"
          >
          <div v-for="(item, index) in menuList" :key="index">
            <el-submenu
               v-if="item.children && item.children.length > 0"
               :index="index.toString()"
             >
               <template #title>
                 <div class="item" :class="{ 'parent-active': isParentActive(index.toString()) }">
                   <img
                    v-if="item.chooseSvgPicture || item.choosePicture"
                     :src="
                       isMenuActive(index.toString()) || isParentActive(index.toString())
                         ? item.chooseSvgPicture
                         : item.choosePicture
                     "
                     class="item-img"
                   />
                   <span :class="{ 'parent-active-text': isParentActive(index.toString()) }">{{ item.catalogName }}</span>
                 </div>
               </template>
              <el-menu-item
                v-for="(val, idx) in item.children"
                :key="`${index}-${idx}`"
                @click="handleMenuItemClick(val, index, idx)"
                :index="index.toString() + '-' + idx"
              >
                <div class="item">
                  <img
                    v-if="val.chooseSvgPicture || val.choosePicture"
                    :src="
                      isMenuActive(index.toString() + '-' + idx)
                        ? val.chooseSvgPicture
                        : val.choosePicture
                    "
                    class="item-img"
                  />
                  <div>{{ val.catalogName }}</div>
                </div>
              </el-menu-item>
            </el-submenu>
            <el-menu-item
              v-else
              :index="index.toString()"
              :key="`${index}`"
              @click="handleMenuItemClick(item, index, -1)"
            >
              <template #title>
                <div class="item">
                  <img
                    v-if="item.chooseSvgPicture || item.choosePicture"
                    :src="
                      isMenuActive(index.toString())
                        ? item.chooseSvgPicture
                        : item.choosePicture
                    "
                    class="item-img"
                  />
                  <span>{{ item.catalogName }}</span>
                </div>
              </template>
            </el-menu-item>
          </div>
        </el-menu>
      </el-scrollbar>
      
      <!-- 收起/展开按钮 -->
      <div class="sidebar-toggle" @click="toggleSidebar">
        <i :class="sidebarCollapsed ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'"></i>
      </div>
    </div>
    
    <div class="content">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item
            v-for="(item, index) in breadcrumbList"
            :key="index"
            >{{ item.name }}</el-breadcrumb-item
          >
        </el-breadcrumb>
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, getCurrentInstance, onMounted, nextTick } from 'vue'
import type { MenuTree } from '@/api/back-management/menu/interface'
// @ts-ignore
import ElScrollbar from 'element-ui/lib/scrollbar'

const breadcrumbList = ref([
  {
    name: '大屏管理',
  },
])

const vm = getCurrentInstance()
const route = vm?.proxy?.$route
const router = vm?.proxy?.$router
const store = vm?.proxy?.$store

// 菜单组件引用
const screenManagerMenu = ref<any>(null)

const menuActive = ref('')
const currentPath = route?.path || ''
const currentUser = vm?.proxy?.$store.state.user.currentUser

// 侧边栏收起状态
const sidebarCollapsed = ref(false)

// 自动展开所有目录
const defaultOpeneds = computed(() => {
  const menus = menuList.value || []
  return menus
    .map((item, index) => {
      if (item.children && item.children.length > 0) {
        return index.toString()
      }
      return null
    })
    .filter((item): item is string => item !== null)
})

// 保持展开状态，防止自动收起
const openedMenus = ref<string[]>([])

// 初始化展开状态
// watch(defaultOpeneds, (newOpeneds) => {
//   openedMenus.value = [...newOpeneds]
// }, { immediate: true })

// 处理子菜单打开事件
const handleSubMenuOpen = (index: string) => {
  if (!openedMenus.value.includes(index)) {
    openedMenus.value.push(index)
  }
}

// 处理子菜单关闭事件 - 阻止自动关闭
const handleSubMenuClose = (index: string) => {
  // 不允许关闭，保持所有菜单都展开
  // 延迟一小段时间后重新打开被关闭的菜单
  nextTick(() => {
    const menu = screenManagerMenu.value
    if (menu && menu.open) {
      menu.open(index)
    }
  })
}



const getIcon = (key: string) => {
  let icon = ''
  switch (key) {
    case 'indicatorManagement':
      icon = 'indicator-management'
      break
    case 'screenConfig':
      icon = 'screen-config'
      break
  }
  return icon
}

const menuList = computed(() => {
  if (!currentUser?.moduleTree || !currentUser.moduleTree[0]?.children) {
    return []
  }

  const treeData = currentUser.moduleTree[0].children.filter(
    (i: MenuTree) => i.code === 'screenManagement'
  ) as MenuTree[]

  if (!treeData[0]?.children) {
    return []
  }

  const menus = treeData[0].children

  menus.forEach((menu: any) => {
    menu.icon = getIcon(menu.code || '')
    menu.name = menu.catalogName // 添加name属性
    // 添加路径映射
    menu.routePath = getRoutePathByCode(menu.code || '')
    if (menu.children) {
      menu.children.forEach((child: any) => {
        child.icon = getIcon(child.code || '')
        child.name = child.catalogName // 添加name属性
        // 添加路径映射
        child.routePath = getRoutePathByCode(child.code || '')
      })
    }
  })

  return menus || []
})

// 根据菜单code获取对应的路由路径
const getRoutePathByCode = (code: string) => {
  switch (code) {
    case 'indicatorManagement':
      return '/screen-management/indicator-management'
    case 'screenConfig':
      return '/screen-management/screen-config'
    case 'indicatorConfig':
      return '/screen-management/indicator-config'
    case 'reportPlatform':
      return '/screen-management/report-platform'
    case 'projectManagement':
      return '/screen-management/report-platform/project-management'
    case 'templateManagement':
      return '/screen-management/report-platform/template-management'
    default:
      return ''
  }
}

// 判断菜单是否被选中
const isMenuActive = (menuIndex: string) => {
  return menuActive.value === menuIndex
}

// 判断父级菜单是否应该显示选中状态（子菜单被选中时）
const isParentActive = (parentIndex: string) => {
  return menuActive.value.startsWith(parentIndex + '-')
}

// 初始化菜单选中状态
const initMenuActive = () => {
  let found = false
  const path = currentPath

  // 遍历菜单，查找匹配当前路由的菜单项
  menuList.value.forEach((val: any, index: number) => {
    if (val.routePath === path) {
      menuActive.value = index.toString()
      breadcrumbList.value = [
        { name: '大屏管理' },
        { name: val.catalogName || '' },
      ]
      found = true
      return
    }
    if (val.children && val.children.length > 0) {
      val.children.forEach((info: any, idx: number) => {
        if (info.routePath === path) {
          menuActive.value = `${index}-${idx}`
          breadcrumbList.value = [
            { name: '大屏管理' },
            { name: val.catalogName || '' },
            { name: info.catalogName || '' },
          ]
          found = true
          return
        }
      })
    }
  })
}



// 监听菜单数据变化，当菜单数据加载完成后初始化选中状态
if (vm?.proxy) {
  vm.proxy.$watch('menuList', () => {
    if (menuList.value.length > 0) {
      initMenuActive()
    }
  }, { immediate: true })
}

// 立即执行一次初始化
initMenuActive()

const handleMenuItemClick = (item: any, index: number, idx: number) => {
  const name = item.catalogName || item.name || ''
  menuActive.value = idx === -1 ? `${index}` : `${index}-${idx}`
  breadcrumbList.value.length = 1
  breadcrumbList.value.push({
    name,
  })
  const path = item.routePath
  console.log('path :>> ', path)
  if (path && router) {
    router.push(path)
  } else if (router) {
    router.push('/screen-management')
  }
}

// 切换侧边栏收起/展开状态
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 初始化时检查是否为汇报平台页面，如果是则默认收起
onMounted(() => {
  if (currentPath.includes('/screen-management/report-platform')) {
    sidebarCollapsed.value = true
  }
})

// 监听路由变化，汇报平台页面默认收起侧边栏
watch(() => route?.path, (newPath) => {
  if (newPath && newPath.includes('/screen-management/report-platform')) {
    sidebarCollapsed.value = true
  }
})
</script>

<style lang="scss" scoped>
.main-container {
  height: 100%;

  :deep(.query-content) {
    padding-left: 20px;
    width: 100%;
    line-height: 62px;
    border-bottom: 1px solid #eeeff5;
    margin-bottom: 20px;

    .el-form {
      height: 80px;
      align-items: center;
      display: flex;
      &-item {
        display: flex;
        align-items: center;
        height: 40px;

        .el-form-item__content {
          display: flex;
          align-items: center;
        }

        .el-button {
          padding-bottom: 0;
          padding-top: 0;
          line-height: 100%;
        }
      }
    }
  }

  :deep(.base-map-resource-content) {
    .query-content {
      box-sizing: border-box;
    }

    .table {
      box-sizing: border-box;
    }
    .el-pagination {
      display: flex;
    }
  }
}
.sidebar-container {
  position: relative;
  width: 256px;
  min-width: 256px;
  max-width: 256px;
  background: #ffffff;
  border-right: 1px solid #e0e0e0;
  transition: all 0.3s ease;
  flex-shrink: 0;

  &.collapsed {
    width: 64px;
    min-width: 64px;
    max-width: 64px;
  }
}

.sidebar-toggle {
  position: absolute;
  top: 50%;
  right: -12px;
  width: 24px;
  height: 24px;
  background: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
  transition: all 0.3s ease;
  transform: translateY(-50%);

  &:hover {
    background: #f5f7fa;
    border-color: #409eff;
    
    i {
      color: #409eff;
    }
  }

  i {
    font-size: 12px;
    color: #666;
    transition: color 0.3s ease;
  }
}

.screenManagerMenu {
  width: 100%;
  height: 100%;

  :deep(.svg-icon) {
    svg {
      width: 16px;
      height: 16px;
      color: #adb8ca;
    }
  }

  :deep(.is-active) {
    .el-sub-menu__title {
      color: #409eff !important;
    }

    .svg-icon {
      svg {
        color: #409eff !important;
      }
    }
  }

  // 父级菜单选中状态样式
  :deep(.el-submenu__title) {
    .item.parent-active {
      .parent-active-text {
        color: #409eff !important;
      }
    }
  }

  :deep(.el-menu-item) {
    height: 60px;
    line-height: 60px;
    display: flex;
    align-items: center;
    box-sizing: border-box;

    .item {
      height: 100% !important;
      line-height: 1 !important;
    }

    &.is-active {
      background: #ecf5ff !important;
      color: #409eff !important;
      border-radius: 4px;

      .svg-icon {
        svg {
          color: #409eff !important;
        }
      }
    }
  }

  // 收起状态下的样式
  &.menu-collapsed {
    width: 64px !important;
    
    :deep(.el-menu-item) {
      text-align: center;
      padding: 0 20px !important;
      
      .item {
        justify-content: center !important;
        width: 100% !important;
        height: 60px !important;
        display: flex !important;
        align-items: center !important;
        
        span,
        div {
          display: none !important;
        }
        
        .item-img {
          margin: 0 !important;
          display: block !important;
          width: 20px !important;
          height: 20px !important;
        }
      }
    }
    
    :deep(.el-submenu__title) {
      text-align: center;
      padding: 0 20px !important;
      
      .item {
        justify-content: center !important;
        width: 100% !important;
        height: 60px !important;
        display: flex !important;
        align-items: center !important;
        
        span {
          display: none !important;
        }
        
        .item-img {
          margin: 0 !important;
          display: block !important;
          width: 20px !important;
          height: 20px !important;
        }
      }
      
      .el-submenu__icon-arrow {
        display: none !important;
      }
    }
    
    :deep(.el-submenu) {
      .el-menu-item {
        text-align: center;
        padding: 0 20px !important;
        
        .item {
          justify-content: center !important;
          width: 100% !important;
          height: 60px !important;
          display: flex !important;
          align-items: center !important;
          
          span,
          div {
            display: none !important;
          }
          
          .item-img {
            margin: 0 !important;
            display: block !important;
            width: 20px !important;
            height: 20px !important;
          }
        }
      }
    }
  }

  .item {
    display: flex;
    align-items: center;
    height: 100%;
    line-height: 1;
    box-sizing: border-box;

    &-img {
      width: 20px;
      height: 20px;
      margin-right: 5px;
      flex-shrink: 0;
    }

    &-icon {
      height: 20px;
      width: 20px;
      margin-right: 5px;
      flex-shrink: 0;
    }

    span,
    div {
      line-height: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

:deep(.el-sub-menu) {
  .el-menu-item {
    padding-left: 47px !important;
    height: 60px;
    line-height: 60px;
    display: flex;
    align-items: center;

    .item {
      height: 100% !important;
      line-height: 1 !important;
    }

    &.is-active {
      background: #ecf5ff !important;
      color: #409eff !important;
      border-radius: 4px;
      margin: 0 8px;

      .svg-icon {
        svg {
          color: #409eff !important;
        }
      }
    }
  }
  
  // 收起状态下子菜单样式
  .menu-collapsed & {
    .el-menu-item {
      text-align: center;
      padding: 0 20px !important;
      margin: 0 !important;
      
      .item {
        justify-content: center !important;
        width: 100% !important;
        height: 60px !important;
        display: flex !important;
        align-items: center !important;
        
        span,
        div {
          display: none !important;
        }
        
        .item-img {
          margin: 0 !important;
          display: block !important;
          width: 20px !important;
          height: 20px !important;
        }
      }
    }
  }
}

.container {
  width: 100%;
  height: 100%;
  display: flex;

  :deep(.el-scrollbar) {
    height: 100%;
    
    .el-scrollbar__wrap {
      .el-scrollbar__view {
        height: 100%;

        .el-menu {
          border-right: none;
          
          // 确保收起状态下菜单项可见
          &.menu-collapsed {
            overflow: visible;
            width: 64px;
          }
        }
      }
    }
  }

  :deep(.screen-form) {
    position: relative;
    .screen-button {
      position: absolute;
      right: 16px;
    }
  }

  .content {
    box-sizing: border-box;
    width: calc(100% - 256px);
    height: 100%;
    background-color: #f0f4f9;
    padding: 14px 20px 20px 20px;
    transition: width 0.3s ease;
    overflow: auto;

    :deep(.el-breadcrumb) {
      margin-bottom: 13px;
    }
  }

  .sidebar-container.collapsed + .content {
    width: calc(100% - 64px);
  }

  :deep(.el-submenu__title) {
    height: 60px;
    line-height: 60px;
    display: flex;
    align-items: center;

    .item {
      height: 100% !important;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 700;
      line-height: 1 !important;
    }
  }

  :deep(.el-menu) {
    > div > .el-menu-item {
      height: 60px;
      line-height: 60px;
      display: flex;
      align-items: center;

      .item {
        height: 100% !important;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 700;
        line-height: 1 !important;
      }
    }
  }
}
</style>
<style lang="scss">
.outline-dialog {
  //width: 462px;
  //background: #ffffff;
  //border-radius: 4px;

  .el-dialog__footer {
    padding-top: 30px !important;
    border-top: 1px solid #e5e5e5;
  }

  .el-dialog__header {
    border-bottom: 1px solid #e5e5e5;

    .el-dialog__title {
      width: 64px;
      height: 16px;
      font-size: 16px;
      font-weight: bold;
      color: #27475f;
    }
  }

  .dialog-footer {
    width: 100%;
    height: 100%;
    text-align: center;
  }
}
</style>
